﻿namespace FFF.Test.Application.AppServices.PublicService.VerificationCode
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;
    using System.Threading.Tasks;
    using Abp.Application.Services;
    using Abp.Auditing;
    using Abp.Domain.Uow;
    using Abp.EntityFrameworkCore;
    using Abp.Runtime.Caching;
    using Abp.UI;
    using Abp.Web.Models;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using FFF.Test.Application.AppServices;
    using FFF.Test.DataAccess.Framework;
    using FFF.Test.Entity;
    using FFF.Test.Util.Consts;
    using FFF.Test.Util.Web;
    using Ydm.Extensions;
    using Ydm.Helper;

    /// <summary>
    /// VerificationCode的管理对象
    /// </summary>
    [YdmApiVersionAttribute(Version = "My")]
    public class VerificationCodeAppService : YdmAbpAppServiceBase, IVerificationCodeAppService
    {
        private readonly ICacheManager _cacheManager;
        private readonly IHttpContextAccessor _httpContext;
        private readonly IDbContextProvider<MyDbContext> _dbContextProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="VerificationCodeAppService"/> class.
        /// VerificationCode构造方法
        /// </summary>
        /// <param name="cacheManager">缓存服务</param>
        /// <param name="httpContext">context</param>
        /// <param name="dbContextProvider">dbcontext</param>
        public VerificationCodeAppService(
            ICacheManager cacheManager,
            IHttpContextAccessor httpContext,
             IDbContextProvider<MyDbContext> dbContextProvider
            )
        {
            this._cacheManager = cacheManager;
            this._httpContext = httpContext;
            this._dbContextProvider = dbContextProvider;
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns>文件存储的id的值</returns>
        [HttpGet]
        [AllowAnonymous]
        [WrapResult(WrapOnSuccess = false, WrapOnError = false)]
        [UnitOfWork(isTransactional: false)]
        public async Task<FileContentResult> GenVerificationCode()
        {
            string code = YdmVerifyCodeHelper.GetSingleObj().CreateVerifyCode(YdmVerifyCodeHelper.VerifyCodeType.MixVerifyCode);
            this._httpContext.HttpContext.Session.SetString(AppConfigConsts.ValidateCodeStr, code);
            var bitmap = YdmVerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, System.DrawingCore.Imaging.ImageFormat.Gif);

            FileContentResult returnFile = new FileContentResult(stream.ToArray(), "image/gif");
            return await Task.FromResult(returnFile);

        }
    }
}